package com.mylib.libcore.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import android.view.ViewGroup;
import android.widget.ImageView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mylib.libcore.R;
import com.mylib.libcore.glide.GlideApp;
import com.mylib.widget.transformer.ImgCornerTransform;


import java.io.File;

import me.jessyan.autosize.utils.ScreenUtils;

import static com.mylib.libcore.glide.GlideOptions.bitmapTransform;

/**
 * Glide 图片加载框架
 * <p>
 * Glide加载图片的封装，圆形、圆角，模糊等处理操作
 * <p>
 * Glide默认使用httpurlconnection协议，可以配置为OkHttp
 * <p>
 * 磁盘缓存的策略：
 * all:缓存源资源和转换后的资源
 * none:不作任何磁盘缓存
 * source:缓存源资源
 * result：缓存转换后的资源
 */
public class GlideUtil {

    private static GlideUtil mInstance;

    private GlideUtil() {
    }

    public static GlideUtil getInstance() {
        if (mInstance == null) {
            synchronized (GlideUtil.class) {
                if (mInstance == null) {
                    mInstance = new GlideUtil();
                }
            }
        }
        return mInstance;
    }

    /**
     * 常量
     */
    static class Contants {
        public static final int BLUR_VALUE = 20; //模糊
        public static final int CORNER_RADIUS = 20; //圆角BlurTransformation
        public static final float THUMB_SIZE = 0.5f; //0-1之间  10%原图的大小
    }

    ///////////////////////////////////////  具 体 方 法  ////////////////////////////////////////////

    /**
     * 默认glide，不做任何处理，glide 从字符串中加载图片（网络地址或者本地地址）
     */
    public static void intoDefault(Context context, String url, ImageView view) {
        Glide.with(context).load(url).into(view);
    }

    /**
     * 默认glide，不做任何处理，加载资源图片
     */
    public static void intoDefault(Context context, int id, ImageView view) {
        Glide.with(context).load(id).into(view);
    }

    /**
     * glide 从文件中加载图片
     */
    public static void into(Context context, File file, ImageView view, int defaultId) {
        if(UIUtils.isEmpty(file)){
            return;
        }
        GlideApp.with(context).load(file)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(defaultId)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .centerCrop() // 缩放图片让图片充满整个ImageView的边框，然后裁掉超出的部分
                .priority(Priority.NORMAL) //下载的优先级
                .into(view);
    }




    /**
     * glide 从URI中加载图片
     */
    public static void into(Context context, Uri uri, ImageView view, int defaultId) {
        if(UIUtils.isEmpty(uri)){
            return;
        }
        GlideApp.with(context).load(uri)
                .placeholder(defaultId)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .centerCrop() // 缩放图片让图片充满整个ImageView的边框，然后裁掉超出的部分
                .priority(Priority.NORMAL) //下载的优先级
                .into(view);
    }

    public static void getRealImageStyle(Context mContext,String url,ImageView ivPic){
        if(UIUtils.isEmpty(url)){
            return;
        }
       int pic_width =  MyScreenUtils.getScreenWidth(mContext);
       int pic_height =  MyScreenUtils.getScreenHeight(mContext);
        if(pic_width<360){
            pic_width = 360;
        }
        if(pic_height<680){
            pic_height = 680;
        }
        //获取图片真正的宽高
        int finalPic_width = pic_width;
        int finalPic_height = pic_height;
        GlideApp.with(mContext)
                .asBitmap()
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int width = resource.getWidth();
                        int height = resource.getHeight();
                        //  Log.d("SimpleTarget",path+"="+width+"="+height+"="+pic_width+"="+pic_height);
                        if(width>=height && height>0 && width>0){
                            GlideUtil.showImageWidthRatio(mContext,url,ivPic, finalPic_width);
                        }else {
                            GlideUtil.showImageHeightRatio(mContext,url,ivPic, finalPic_height);
                        }
                    }
                });
    }

    /**
     * 加载图片-自适应
     */
    public static void loadImgAutoSize(final Context mContext, String imagePath, final ImageView imageView) {
        if(UIUtils.isEmpty(imagePath)){
            return;
        }
        if(checkUrlIsGif(imagePath)){
            loadGifThumbnailImage(mContext,imageView,imagePath);
        }else {
            GlideApp.with(mContext)
                    .asBitmap()
                    .load(imagePath+"")
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            int width = resource.getWidth();
                            int height = resource.getHeight();
                            //  Log.d("SimpleTarget",path+"="+width+"="+height+"="+pic_width+"="+pic_height);
                            if(width>=height && height>0 && width>0){
                                GlideUtil.showImageWidthRatio(mContext,imagePath,imageView,imageView.getWidth());
                            }else {
                                GlideUtil.showImageHeightRatio( mContext,imagePath,imageView,imageView.getHeight());
                            }
                        }
                    });
        }

    }


    //以图片宽度为基准
    public static void showImageWidthRatio(Context context, String url, final ImageView imageView, final int width){
        if(UIUtils.isEmpty(url) || UIUtils.isEmpty(imageView)){
            return;
        }
        GlideApp.with(context)
                .asBitmap()
                .placeholder(R.drawable.ic_zhanwei_message)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .priority(Priority.NORMAL) //下载的优先级
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth=resource.getWidth();
                        int imageHeight=resource.getHeight();
                        int height = width * imageHeight / imageWidth;
                        ViewGroup.LayoutParams params=imageView.getLayoutParams();
                        params.height=height;
                        params.width=width;
                        imageView.setImageBitmap(resource);
                    }
                });
    }

    //以图片高度为基准
    public static void showImageHeightRatio(Context context, String url, final ImageView imageView, final int height){
        if(UIUtils.isEmpty(url) || UIUtils.isEmpty(imageView)){
            return;
        }
        GlideApp.with(context)
                .asBitmap()
                .placeholder(R.drawable.ic_zhanwei_message)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .priority(Priority.NORMAL) //下载的优先级
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth=resource.getWidth();
                        int imageHeight=resource.getHeight();
                        int width = height * imageHeight / imageWidth;
                        ViewGroup.LayoutParams params=imageView.getLayoutParams();
                        params.height=height;
                        params.width=width;
                        imageView.setImageBitmap(resource);
                    }
                });
    }

    /**
     * glide 通过指定的大小从字符串中加载图片（网络地址或者本地地址）
     */
    public static void into(Context context, String url, ImageView view, int width, int height, int defaultId) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        GlideApp.with(context)
                .load(url)
                .placeholder(R.drawable.ic_zhanwei_message)
                .error(R.drawable.store_album_choose)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .centerCrop() // 缩放图片让图片充满整个ImageView的边框，然后裁掉超出的部分
                .priority(Priority.NORMAL) //下载的优先级
                .override(width, height)//指定图片大小
                .into(view);
    }




    /**
     * glide 从字符串中加载图片（网络地址或者本地地址）,不裁剪
     */
    public static void intoImg(Context context, String url, ImageView view) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadGifThumbnailImage(context,view,url);
        }else {
            GlideApp.with(context).load(url)
                    .placeholder(R.drawable.ic_zhanwei_message)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                    .priority(Priority.NORMAL) //下载的优先级
                    .into(view);
        }

    }
    /**
     * glide 从字符串中加载图片（网络地址或者本地地址）,不裁剪
     */
    public static void intoHeadImg(Context context, String url, RoundedImageView view) {
        if(UIUtils.isEmpty(url))    return;
        if(checkUrlIsGif(url)){
            loadGifThumbnailImage(context,view,url);
        }else {
            GlideApp.with(context).load(url)
                    .placeholder(R.drawable.img_mine_head)
                    .error(R.drawable.img_mine_head)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                    .priority(Priority.NORMAL) //下载的优先级
                    .into(view);
        }
    }


    /**
     * glide 从字符串中加载图片（网络地址或者本地地址）,
     */
    public static void into(Context context, String url, ImageView view) {
        if(UIUtils.isEmpty(url) || UIUtils.isEmpty(view)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadGifThumbnailImage(context,view,url);
        }else {
            GlideApp.with(context).load(url)
                    .placeholder(R.drawable.button_white_circle_solid_selector_5)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                    .centerCrop() // 缩放图片让图片充满整个ImageView的边框，然后裁掉超出的部分
                    .priority(Priority.NORMAL) //下载的优先级
                    .into(view);
        }

    }


    /**
     * glide 从字符串中加载图片（网络地址或者本地地址）,
     */
    public static void intoNewsPic(Context context, String url, ImageView view) {
        if(UIUtils.isEmpty(url) || UIUtils.isEmpty(view)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadGifThumbnailImage(context,view,url);
        }else {
            GlideApp.with(context).load(url)
                    .placeholder(R.color.white)
                    .error(R.color.white)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                    .centerCrop() // 缩放图片让图片充满整个ImageView的边框，然后裁掉超出的部分
                    .priority(Priority.NORMAL) //下载的优先级
                    .into(view);
        }

    }


    /**
     * 加载gif
     *
     * @param context
     * @param imageView
     * @param imgUrl
     * @param placeholder 图片资源ID
     */
    public void loadGifImage(Context context, ImageView imageView, String imgUrl, int placeholder) {
        if(UIUtils.isEmpty(imgUrl)){
            return;
        }
        GlideApp.with(context).asGif()
                .load(imgUrl)
                .priority(Priority.NORMAL) //下载的优先级
                .diskCacheStrategy(DiskCacheStrategy.ALL) //缓存策略
                .error(placeholder)
                .into(imageView);

    }

    /**
     * 加载gif的缩略图
     *
     * @param context
     * @param imageView
     * @param imgUrl
     */
    public static void loadGifThumbnailImage(Context context, ImageView imageView, String imgUrl) {
        if(UIUtils.isEmpty(imgUrl)){
            return;
        }
        GlideApp.with(context).asGif()
                .load(imgUrl)
                .priority(Priority.NORMAL) //下载的优先级
                .diskCacheStrategy(DiskCacheStrategy.ALL) //缓存策略
                .placeholder(R.drawable.button_line_circle_solid_selector_5)
                .error(R.drawable.button_line_circle_solid_selector_5)
                .thumbnail(Contants.THUMB_SIZE)
                .into(imageView);
    }
    /**
     * 加载gif的缩略图
     *
     * @param context
     * @param imageView
     * @param imgUrl
     */
    public static void loadNiceGifThumbnailImage(Context context, RoundedImageView imageView, String imgUrl) {
        if(UIUtils.isEmpty(imgUrl)){
            return;
        }
        GlideApp.with(context).asGif()
                .load(imgUrl)
                .priority(Priority.NORMAL) //下载的优先级
                .diskCacheStrategy(DiskCacheStrategy.ALL) //缓存策略
                .placeholder(R.drawable.button_line_circle_solid_selector_5)
                .error(R.drawable.button_line_circle_solid_selector_5)
                .thumbnail(Contants.THUMB_SIZE)
                .into(imageView);
    }



    /**
     * 恢复请求，一般在停止滚动的时候
     *
     * @param context
     */
    public void resumeRequests(Context context) {
        Glide.with(context).resumeRequests();
    }

    /**
     * 暂停请求 正在滚动的时候
     *
     * @param context
     */
    public void pauseRequests(Context context) {
        Glide.with(context).pauseRequests();
    }

    /**
     * 清理磁盘缓存
     *
     * @param mContext
     */
    public static void GuideClearDiskCache(Context mContext) {
        //理磁盘缓存 需要在子线程中执行
        Glide.get(mContext).clearDiskCache();
    }

    /**
     * 清理内存缓存
     *
     * @param mContext
     */
    public static void GuideClearMemory(Context mContext) {
        //清理内存缓存  可以在UI主线程中进行
        Glide.get(mContext).clearMemory();
    }


    /**
     * 加载圆角图片
     */
    public static void loadFilletPicNice(final Context context, String url, final RoundedImageView imageView,int angle) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadNiceGifThumbnailImage(context,imageView,url);
        }else {
            ImgCornerTransform transformation = new ImgCornerTransform(context, dip2px(context, angle));
//只是绘制左上角和右上角圆角
            transformation.setExceptCorner(false, false, true, true);
            GlideApp.with(context)
                    .asBitmap()
                    .load(url)
                    .skipMemoryCache(true)
                    .placeholder(R.drawable.button_line_circle_solid_selector_5)
                    .error(R.drawable.button_line_circle_solid_selector_5)
                    .transform(transformation)
                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                    .into(imageView);
        }

    }
    public static void loadFilletPicNiceCircle(final Context context, String url, final RoundedImageView imageView,int angle) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadNiceGifThumbnailImage(context,imageView,url);
        }else {
            ImgCornerTransform transformation = new ImgCornerTransform(context, dip2px(context, angle));
//只是绘制左上角和右上角圆角
            transformation.setExceptCorner(false, false, false, false);
            GlideApp.with(context)
                    .asBitmap()
                    .load(url)
                    .skipMemoryCache(true)
                    .placeholder(R.drawable.button_line_circle_solid_selector_5)
                    .error(R.drawable.button_line_circle_solid_selector_5)
                    .transform(transformation)
                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                    .into(imageView);
        }
    }

    /**
     * glide 从文件中加载图片
     */
    public static void intoVideo(Context context, String url, ImageView view ) {
        if(UIUtils.isEmpty(url) || UIUtils.isEmpty(view)){
            return;
        }
        GlideApp.with(context).load(url)
                //            DiskCacheStrategy.NONE 啥也不缓存
                //            DiskCacheStrategy.SOURCE 只缓存全尺寸图. 上面例子里的1000x1000像素的图片
                //            DiskCacheStrategy.RESULT 只缓存最终降低分辨后用到的图片
                //            DiskCacheStrategy.ALL 缓存所有类型的图片 (默认行为)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .skipMemoryCache(true)//跳过内存缓存
                .placeholder(R.color.transparent)
                .error(R.color.transparent)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .centerCrop() // 缩放图片让图片充满整个ImageView的边框，然后裁掉超出的部分
                .priority(Priority.NORMAL) //下载的优先级
                .into(view);
    }


    /**
     * 加载圆角图片
     */
    public static void loadFilletPic(final Context context, String url, final ImageView imageView,int angle) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadGifThumbnailImage(context,imageView,url);
        }else {
            ImgCornerTransform transformation = new ImgCornerTransform(context, dip2px(context, angle));
//只是绘制左上角和右上角圆角
            transformation.setExceptCorner(false, false, false, false);
            GlideApp.with(context)
                    .asBitmap()
                    .load(url)
                    .skipMemoryCache(true)
                    .placeholder(R.drawable.button_line_circle_solid_selector_5)
                    .error(R.drawable.button_line_circle_solid_selector_5)
                    .transform(transformation)
                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                    .into(imageView);
        }


    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /**
     * 加载圆角图片-自定义四个角度
     */
    public static void loadFilletPicCoustom(final Context context, String url, final RoundedImageView imageView) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        GlideApp.with(context).load(url)
                .placeholder(R.drawable.ic_zhanwei_message)
                .dontAnimate()//去掉glide 自带的效果，防止加载自定义控件时只显示替换图
                .priority(Priority.NORMAL) //下载的优先级
                .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                .into(imageView);
    }


    /**
     * 加载圆形图片
     *
     * @param context
     * @param url
     * @param imageView
     */
    public static void loadCirclePic(final Context context, String url, final ImageView imageView) {
        if(UIUtils.isEmpty(url)){
            return;
        }
        if(checkUrlIsGif(url)){
            loadGifThumbnailImage(context,imageView,url);
        }else {
            GlideApp.with(context)
                    .asBitmap()
                    .load(url)
                    .placeholder(R.drawable.img_mine_head)
                    .error(R.drawable.img_mine_head)
                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                    .into(new BitmapImageViewTarget(imageView) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            RoundedBitmapDrawable circularBitmapDrawable =
                                    RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                            circularBitmapDrawable.setCircular(true);
                            imageView.setImageDrawable(circularBitmapDrawable);
                        }
                    });
        }

    }
    /**
     * 加载头像
     *
     * @param context
     * @param url
     * @param imageView
     */
    public static void loadhead(final Context context, String url, final ImageView imageView) {
                if(UIUtils.isEmpty(url)){
                    return;
                }
                if(checkUrlIsGif(url)){
                    loadGifThumbnailImage(context,imageView,url);
                }else {
                    GlideApp.with(context)
                            .asBitmap()
                            .load(url)
                            .placeholder(R.drawable.img_mine_head)
                            .error(R.drawable.img_mine_head)
                            .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                            .into(new BitmapImageViewTarget(imageView) {
                                @Override
                                protected void setResource(Bitmap resource) {
                                    RoundedBitmapDrawable circularBitmapDrawable =
                                            RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                                    circularBitmapDrawable.setCircular(true);
                                    imageView.setImageDrawable(circularBitmapDrawable);
                                }
                            });
                }

    }
    private static boolean checkUrlIsGif(String url){
        if(UIUtils.isEmpty(url)){
            return false;
        }
        if(!UIUtils.isEmpty(url) && url.length()>4){
            int urlLength= url.length();
            String hzmUrl = url.substring(urlLength-3,urlLength);
            if(hzmUrl.equals("gif") || hzmUrl.equals("GIF")){
                return  true;
            }else {
                return  false;
            }
        }else {
            return false;
        }

    }
}
